﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper;
using Telerik.OpenAccess;
using YuYuKiCms.Dal.Interface;
using YuYuKiCms.Dal.Model;

namespace YuYuKiCms.Dal.Repository
{
    internal class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    {
        protected readonly IYuyukiModelUnitOfWork Db;

        public BaseRepository(IYuyukiModelUnitOfWork db)
        {
            Db = db;
        }

        public T GetId<TKey>(TKey id)
        {
            return Db.GetAll<T>().FirstOrDefault(model => model.FieldValue<TKey>("Id").Equals(id));
        }
        
        public void SaveChange()
        {
            Db.SaveChanges();
        }

        public void InsertOrUpdate<TKey>(T model, TKey id)
        {
            var modelFromDb = GetId(id);
            if (modelFromDb == null)
            {
                // Add
                Db.Add(model);
            }
            else
            {
                // Update
                Mapper.DynamicMap(model, modelFromDb);
            }

            Db.SaveChanges();
        }

        public void Delete(T model)
        {
            Db.Delete(model);
            Db.SaveChanges();
        }

        public IEnumerable<T> GetAll(Expression<Func<T, bool>> isValid = null)
        {
            isValid = isValid ?? (arg => true);
            return Db.GetAll<T>().Where(isValid);
        }
    }
}